package com.hlkj.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBPoolUtil {
	static Properties properties = new Properties();
	static DataSource datasource;
	static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	static {
		try {
			properties.load(DBPoolUtil.class.getClassLoader()
					.getResourceAsStream("jdbc.properties"));
			datasource = BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized static Connection getConnection() throws SQLException {
		Connection conn = threadLocal.get();
		if (conn == null) {
			System.out.println("====新建立了一次连接====");
			conn = datasource.getConnection();
			threadLocal.set(conn);
		}
		return conn;
	}

	public synchronized static void close() throws SQLException {
		Connection conn = threadLocal.get();
		threadLocal.remove();
		threadLocal.set(null);
		if (conn != null && conn.isClosed() == false) {
			System.out.println("====关闭了一次连接====");
			conn.close();
		}
	}

	// ==================以下处理事物====================
	public static void startTransaction() {
		try {
			Connection conn = threadLocal.get();
			if (conn == null) { // 如果ThreadLoacl中没有，就从DataSource中获取
				conn = datasource.getConnection();
				threadLocal.set(conn); // 存入
			}
			conn.setAutoCommit(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void rollback() {// 回滚事务，catch处调用rollbakc方法
		try {
			Connection conn = threadLocal.get();
			if (conn != null)
				conn.rollback();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void commit() { // 在finally里调用提交commint方法
		try {
			Connection conn = threadLocal.get();
			if (conn != null)
				conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws SQLException {
		DBPoolUtil.getConnection();
		System.out.println(DBPoolUtil.getConnection());
		DBPoolUtil.close();
		System.out.println(DBPoolUtil.getConnection());

	}
}
